package com.onlyxiahui.wofa.server.socket.netty.tcp.impl;

import com.onlyxiahui.framework.action.dispatcher.general.GeneralMessageHandler;
import com.onlyxiahui.wofa.server.net.core.session.SocketSessionHandler;
import com.onlyxiahui.wofa.server.socket.netty.common.coder.NettyCodecCreater;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.ssl.SslContext;

/**
 * 
 * Description <br>
 * Date 2019-07-21 18:38:42<br>
 * 
 * @author XiaHui [onlovexiahui@qq.com]<br>
 * @since 1.0.0
 */
public class SocketServerInitializer extends ChannelInitializer<SocketChannel> {

	private GeneralMessageHandler messageHandler;
	private SocketSessionHandler sessionHandler;
	private NettyCodecCreater coderCreater;
	private final SslContext sslContext;

	public SocketServerInitializer(
			GeneralMessageHandler messageHandler,
			SocketSessionHandler sessionHandler,
			NettyCodecCreater coderCreater,
			SslContext sslContext) {
		this.messageHandler = messageHandler;
		this.sessionHandler = sessionHandler;
		this.coderCreater = coderCreater;
		this.sslContext = sslContext;
	}

	@Override
	public void initChannel(SocketChannel sh) throws Exception {
		ChannelPipeline pipeline = sh.pipeline();

		if (sslContext != null) {
			pipeline.addLast(sslContext.newHandler(sh.alloc()));
		}

		pipeline.addLast("coder", coderCreater.get());
		pipeline.addLast("handler", new SocketHandler(messageHandler, sessionHandler));
	}
}
